package com.nali.dal.statement.function.formatter.date;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;

import com.nali.dal.statement.function.AbstractDataHandler;
import com.nali.dal.statement.function.FunctionArgument;
import com.nali.dal.statement.function.FunctionException;

/**
 * DateBeforeSysdate<br>&nbsp;
 * 返回一个距离当前时间的一个日期
 * arg1=count
 * arg2=时间单位，默认为秒
 * arg3=往前之后的truncate单位，默认不truncate（先before后truncate）
 * arg4=truncate的修正值，+n truncate单位，默认是不修正（一般是加1用来向下取整）
 * @author sam Created on 2011-4-16
 */
@Component
public class DateBeforeSysdate extends AbstractDataHandler<Date> {//TODO 跟dateDecrease整合
	@Override
	public void validate(List<FunctionArgument> arguments) throws FunctionException {
		checkSize(arguments, 1, 4);
	}
	
	@Override
	public Date handle(List<Object> argList) throws FunctionException {
		Date rlt = new Date();
		Number count = (Number) argList.get(0);
		TimeUnit timeUnit;
		if(argList.size() > 1) {
			String timeUnitName = (String) argList.get(1);
			timeUnit = TimeUnit.getTimeUnit(timeUnitName);
		} else {
			timeUnit = TimeUnit.SECOND;
		}
		rlt = timeUnit.decr(rlt, count.intValue());
		if(argList.size() > 2) {
			String truncateUnitName = (String) argList.get(2);
			TimeUnit truncateUnit = TimeUnit.getTimeUnit(truncateUnitName);
			rlt=truncateUnit.convert(rlt);
			if(argList.size() > 3) {
				int fix = ((Number)argList.get(3)).intValue();
				rlt=truncateUnit.decr(rlt, -fix);
			}
		}
		return rlt;
	}
}
